from utils.global_utils import *


def event_scale(events: np.ndarray, scale: float) -> np.ndarray:
    if events is None:
        return None
    events = events.copy()
    if not events.shape[0]:
        return events
    events[:, -2:] = np.floor(events[:, -2:] * scale).astype(events.dtype)
    return events


def event_denoise(events: np.ndarray, shape: Tuple[int, int], k: int = 3, th: int = 5) -> np.ndarray:
    if events is None:
        return None
    events = events.copy()
    if not events.shape[0]:
        return events
    
    y, x = events[:, -2].astype(np.uint64), events[:, -1].astype(np.uint64)
    mat = np.zeros(shape, dtype = np.uint64)
    mat[y, x] = 1

    kernel = np.ones((k, k), dtype = np.uint64)
    counts = ndimage.convolve(mat, kernel, mode = "constant")
    mask = (counts >= th) & (mat == 1)

    y, x = np.where(mask)
    new_events = events[np.isin(events[:, -2], y) & np.isin(events[:, -1], x)]
    return new_events